const qiniu = require('qiniu')
const config = require('config')
const path = require('path')
const util = require('utility')
const temp = require('temp')
const bucket = 'image'
const accessKey = config.qiniu.accessKey;
const secretKey = config.qiniu.secretKey;
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const request = require('request')

const downloadUrlToFile = (remoteUrl, localPath) => {
  const http = require('http')
  const https = require('https')
  const fs = require('fs')
  const url_mod = require('url')
  const protocol = url_mod.parse(remoteUrl).protocol
  const req_mod = protocol == 'https:' ? https : http
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(localPath)
    req_mod.get(remoteUrl, function(response) {
      response.pipe(file)
      file.on('finish', function() {
        file.close(function () {
          resolve()
        })  // close() is async, call cb after close completes.
      })
    }).on('error', function(err) { // Handle errors
      fs.unlink(dest); // Delete the file async. (But we don't check the result)
      reject(err.message)
    })
  })
}

const uploadRemoteUrl = async (remoteUrl, biz) => {
  temp.track()
  const tempPath = temp.path({suffix: path.extname(remoteUrl) || '.jpg'})
  console.log('remoteUrl', remoteUrl)
  console.log('extname', path.extname(remoteUrl))
  console.log('tempPath', tempPath)
  await downloadUrlToFile(remoteUrl, tempPath)
  const res = await upload(tempPath, biz)
  temp.cleanupSync()
  return res
}

const upload = (localFile, biz) => {
  const formUploader = new qiniu.form_up.FormUploader(config);
  const putExtra = new qiniu.form_up.PutExtra();
  const options = {
    scope: bucket,
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);
  const uploadToken = putPolicy.uploadToken(mac);
  console.log('localFile', path.extname(localFile), localFile)
  const key = (biz ? `${biz}/` : '') + util.md5(localFile) + (path.extname(localFile) || '.jpg')
  
  // 文件上传
  return new Promise((resolve, reject) => {
    formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
      respBody, respInfo) {
      if (respErr) {
        throw respErr;
      }
      if (respInfo.statusCode == 200) {
        resolve({
          url: config.qiniu.imageHost + respBody.key
        })
      } else {
        reject(respInfo.statusCode + ':' + respBody)
      }
    }); 
  })
}

upload(require('path').join(__dirname, './city.js'))

module.exports = {
  uploadRemoteUrl,
  upload
}